import uuid
from http.client import HTTPException
from typing import List, Type

from fastapi import Depends

from core.mysql import SessionLocal
from models.user_model import UserScheme, UserCreate, UserUpdate
from sqlalchemy.orm import Session

from services.db import get_db_session
import datetime


def get_user_service():
    user_service = UserService()
    return user_service


# Dependency


class UserService:

    def get_user_by_id(self, user_id: str, db: Session) -> Type[UserScheme]:
        return db.query(UserScheme).filter(user_id == UserScheme.id).first()

    def get_user_by_username(self, name: str, db: Session = Depends(get_db_session)) -> Type[UserScheme]:
        return db.query(UserScheme).filter(name == UserScheme.username).first()

    def get_user_by_account(self, account: str, db: Session = Depends(get_db_session)):
        return db.query(UserScheme).filter(account == UserScheme.account).first()

    def get_user_by_ids(self, ids: List[str], db: Session = Depends(get_db_session)) -> List[Type[UserScheme]]:
        return db.query(UserScheme).filter(UserScheme.id.in_(ids)).all()

    def list_users(self, page: int, page_size: int, db: Session) -> (list, int):
        return db.query(UserScheme).offset((page - 1) * page_size).limit(page_size).all(), db.query(UserScheme).count()

    def add_user(self, user: UserCreate, db: Session):
        new_user = UserScheme(
            id=uuid.uuid4(),
            username=user.username,
            account=user.account,
            password=user.password,
            male=user.male,
            status=1,
            email=user.email,
            create_by='',
            create_time=datetime.datetime.now(),
            role='1',
        )
        db.add(new_user)
        db.commit()
        return new_user.id

    def delete_user(self, user_id: str, db: Session = Depends(get_db_session)) -> int:
        return db.query(UserScheme).filter(user_id == UserScheme.id).delete()

    def update_user(self, user: UserUpdate, db: Session = Depends(get_db_session)) -> int:
        userdb: Type[UserScheme] = db.query(UserScheme).filter(UserScheme.id == user.id).first()
        if userdb:
            userdb.username = user.username
            userdb.password = user.password
            userdb.update_time = datetime.datetime
            return 1
        else:
            return 0
        # return db.query(User).filter(id == user.id).update(user.dict())

    def login_user(self, account: str, password: str):
        return True

    def logout_user(self):
        return True
